<script setup>
import { useUserStore } from "@/store";
import {
  userLoginService,
  getUsernameById,
  changeUInfoService,
  loginAfterPerfectInfo
} from "@/api/user";
import { onMounted, ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { SUCCESS } from "@/core/constants/HttpStatus";
import { useRouter } from "vue-router";

const userStore = useUserStore();
const router = useRouter();

const userid = ref(""); // 账号
const password = ref(""); // 密码
const rememberMe = ref(false); // 记住密码，默认关闭
const visible = ref(false); //弹窗可见性，默认不可见
const changeFormRef = ref();

// 处理登录
const handleLogin = async () => {
  if (userid.value === "" || password.value === "") {
    ElMessage.error("请输入完整信息");
    return;
  }
  let defaultMessage = "登录失败！";
  // 登录
  try {
    const res = await userLoginService({
      uid: userid.value,
      pw: password.value,
    });
    console.log(res);
    // 解析返回对象
    const {code, data, msg} = res.data;
    // code是字符串类型
    if (code == SUCCESS) {
      userStore.setToken(data.token);
      await userStore.fetchUserInfo();
      // 如果选择了“记住密码”，则将用户名和密码保存到本地存储中
      if (rememberMe.value === true) {
        localStorage.setItem("userid", userid.value);
        localStorage.setItem("password", password.value);
      } else {
        // 如果未选择“记住密码”，则清除本地存储中的用户名和密码
        localStorage.removeItem("userid");
        localStorage.removeItem("password");
      }
      ElMessage({
        message: "登录成功！",
        type: "success",
      });
      // 跳转重定向页面或主页
      console.log("@@route", router.currentRoute.value);
      const currenRoute = router.currentRoute.value;
      const redirect = currenRoute.redirectedFrom?.path;
      await router.push(redirect ||　"/");
    } else if (msg == "用户信息未完善") {
      showDialog();
    } else {
      throw new Error(msg);
    }
  } catch (error) {
    ElMessage.error(error.message || defaultMessage);
  }
};
const showDialog = async () => {
  visible.value = true;
  try {
    const res = await getUsernameById(userid.value);
    console.log(res);
    if (res.data.msg === "查询成功!") {
      userInfoForm.uid = userid.value;
      userInfoForm.urealname = res.data.data;
    } else {
      ElMessage.error(res.data.msg);
    }
  } catch (e) {
    ElMessage.error(e.message || "信息保存失败");
  }
};

// 检查是否记住密码
const checkRemember = () => {
  // 在组件加载时，如果本地存储中有用户名和密码，则自动填充表单
  userid.value = localStorage.getItem("userid") || "";
  password.value = localStorage.getItem("password") || "";
  // 如果有记住密码，则继续选中
  if (userid.value && password.value) {
    rememberMe.value = true;
  } else {
    console.log("没有记住密码");
  }
};

onMounted(() => {
  // 检查是否记住密码
  checkRemember();
});

//首次登录-完善个人信息
//用户个人信息表单
const userInfoForm = reactive({
  uid: "",
  unickname: "",
  urealname: "",
  ugender: "",
  uphone: "",
  umail: "",
  uintro: "",
  uability: "",
});
//用户个人信息表单校验
/**
 * urealname:不能为空，需为汉字
 * unickname:可以为空，不为空时必须为1-10位字符
 * umail:不能为空，要符合基本邮箱写法
 * uphone:可以为空，不为空时要为合法手机号
 */
const userInfoRules = {
  uid: [{ required: true, message: "账号不能为空", trigger: "blur" }],
  urealname: [
    { required: true, message: "请输入真实姓名", trigger: "blur" },
    { pattern: /[\u4e00-\u9fa5]/, message: "姓名需为中文", trigger: "blur" },
  ],
  unickname: [
    { required: true, message: "请输入昵称", trigger: "blur" },
    { min: 1, max: 10, message: "用户名必须是1-10位的字符", trigger: "blur" },
  ],
  ugender: [{ required: true, message: "请选择性别", trigger: "blur" }],
  uphone: [
    { required: true, message: "请输入联系方式", trigger: "blur" },
    {
      pattern:
        /^([0|86|17951])?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/,
      message: "请输入合规手机号",
      trigger: "blur",
    },
  ],
  umail: [
    { required: true, message: "请输入邮箱地址", trigger: "blur" },
    {
      pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/,
      message: "邮箱为非正常写法，请重新输入",
      trigger: "blur",
    },
  ],
};
//完善个人信息并登录
const improveInfo = async () => {
  await changeFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await loginAfterPerfectInfo({
          uid: userInfoForm.uid,
          realname: userInfoForm.urealname,
          nickname: userInfoForm.unickname,
          gender: userInfoForm.ugender,
          phone: userInfoForm.uphone,
          email: userInfoForm.umail,
          intro: userInfoForm.uintro,
          ability: userInfoForm.uability,
        });
        console.log("保存信息：")
        console.log(res);
        const { code, msg } = res.data;
        if (code == SUCCESS) {
          ElMessage.success("信息保存成功！");
          handleLogin();
          visible.value = false;
        } else {
          throw new Error(msg);
        }
      } catch (e) {
        ElMessage.error(e.message || "信息保存失败");
      }
    } else {
      ElMessage.error("信息输入格式有误，请重新检查");
      console.log("表单校验未通过");
    }
  });
};
//退出
const exit = () => {
  visible.value = false;
};
</script>

<template>
  <div class="loginBox">
    <div class="titleBox">
      <span class="title">LOGIN</span>
    </div>
    <div class="accountBox">
      <i class="iconfont icon-zhanghaozhongxinzhanghaoguanli"/>
      <input
          class="inputField"
          type="text"
          placeholder="请输入学号"
          v-model="userid"
          @keyup.enter="handleLogin"
      />
    </div>
    <div class="passwordBox">
      <i class="iconfont icon-mima"/>
      <input
          class="inputField"
          type="password"
          placeholder="请输入密码"
          v-model="password"
          @keyup.enter="handleLogin"
      />
    </div>
    <div class="tipsBox">
      <router-link to="/login/forget" class="tipFont">忘记密码</router-link>
      <input type="checkbox" id="remember" v-model="rememberMe"/>
      <label for="remember">记住密码</label>
    </div>
    <div class="buttonBox">
      <button class="logInButton" @click="handleLogin">登录</button>
    </div>
    <!-- 完善信息弹窗 -->
    <el-dialog title="请完善个人信息后登录" v-model="visible" top="15px" width="70%">
      <el-form
        ref="changeFormRef"
        :model="userInfoForm"
        :rules="userInfoRules"
        label-width="auto"
        label-position="left"
        :inline="true"
        status-icon
      >
        <el-row>
          <el-form-item label="账号:" prop="uid">
            <el-input disabled v-model="userInfoForm.uid"></el-input>
          </el-form-item>
          <el-form-item label="姓名:" prop="urealname">
            <el-input disabled v-model="userInfoForm.urealname"></el-input>
          </el-form-item>
          <el-form-item label="昵称:" prop="unickname">
            <el-input v-model="userInfoForm.unickname"></el-input>
          </el-form-item>

          <el-form-item label="性别:" prop="ugender">
            <el-radio-group v-model="userInfoForm.ugender">
              <el-radio label="女" value="女"></el-radio>
              <el-radio label="男" value="男"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="联系方式:" prop="uphone">
            <el-input v-model="userInfoForm.uphone"></el-input>
          </el-form-item>
          <el-form-item label="邮箱:" prop="umail">
            <el-input v-model="userInfoForm.umail"></el-input>
          </el-form-item>
          <el-form-item label="个人简介:" class="textarea">
            <el-input
              type="textarea"
              v-model="userInfoForm.uintro"
              :rows="5"
            ></el-input>
          </el-form-item>
          <el-form-item label="能力专长:" class="textarea">
            <el-input
              type="textarea"
              v-model="userInfoForm.uability"
              :rows="5"
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row class="buttonrow" type="flex" justify="center">
          <el-form-item>
            <el-button type="primary" @click="improveInfo(userInfoForm)">
              保存并登录
            </el-button>
            <el-button @click="exit">退出</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">
.loginBox {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  // background-color: rgba(250, 246, 246, 0.9);
  border-radius: 8px;
  height: auto;
}

.titleBox {
  display: flex;
  /* 设置为 Flex 容器 */
  align-items: center;
  /* 垂直居中 */
  height: 20%;
  margin-top: 5%;
}

.titleBox span {
  font-size: 30px;
  color: #1e9ab5;
  margin: auto;
  letter-spacing: 5px;
}

.accountBox {
  display: flex;
  /* 设置为 Flex 容器 */
  align-items: center;
  /* 垂直居中 */
  justify-content: center;
  /* 水平居中 */
  height: 8%;
}

.accountBox i {
  display: inline-block;
  font-size: 25px;
  color: rgb(175, 171, 171);
}

.passwordBox {
  display: flex;
  /* 设置为 Flex 容器 */
  align-items: center;
  /* 垂直居中 */
  justify-content: center;
  /* 水平居中 */
  height: 9%;
}

.passwordBox i {
  display: inline-block;
  font-size: 22px;
  color: rgb(175, 171, 171);
}

/*文本框*/
.inputField {
  background-color: transparent;
  width: 60%;
  color: rgb(175, 171, 171);
  border: none;
  box-shadow: none;
  /* 下边框样式 */
  border-bottom: 1px solid #1e9ab5;
  padding: 5px 0;
  text-indent: 10px;
  margin: 8px 5px;
  font-size: 18px;
  letter-spacing: 2px;
}

input::placeholder {
  color: rgb(212, 209, 209);
  font-size: 16px;
}

.tipsBox {
  display: flex;
  justify-content: center;
  font-size: 14px;

  .tipFont {
    margin-right: 40px;
    color: gray;
  }
}

#remember {
  width: 15px;
  margin-right: 2px;
}

.tipsBox label {
  font-size: 14px;
  // margin-right: 17%;
  color: gray;
}

.buttonBox {
  display: flex;
  /* 设置为 Flex 容器 */
  align-items: center;
  /* 垂直居中 */
  justify-content: center;
  /* 水平居中 */
  margin-bottom: 10%;
}

.buttonBox .logInButton {
  width: 50%;
  height: 40px;
  font-size: 18px;
  font-weight: bold;
  color: #ffffff;
  background-color: #1e9ab5;
  border-radius: 8px;
  border: 1px solid white;
}

.bottomBox {
  display: flex;
  /* 设置为 Flex 容器 */
  align-items: center;
  /* 垂直居中 */
  margin-top: 5%;
  margin-bottom: 5%;
}

@media (max-height: 400px) {
  .tipsBox {
    display: none;
  }
}

.el-form {
  margin: 0px auto;
  width: 90%;

  .el-form-item {
    width: 45%;
  }
  .buttonrow {
    .el-form-item {
      width: auto;
    }
  }

  .textarea {
    width: 95%;
  }
}
</style>

